package com.zhuangfei.hpuhelper.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hpu.bean.Score;
import com.hpu.constants.HttpConstants;
import com.hpu.constants.ShareConstants;
import com.hpu.parser.AllScoreParser;
import com.hpu.service.AllScoreService;
import com.hpu.service.LoginService;
import com.hpu.tools.ShareTools;
import com.zhuangfei.generalpage.BaseFragment;
import com.zhuangfei.hpuhelper.tools.DefaultHandler;
import com.zhuangfei.smartalert.core.ChooseViewAlert;
import com.zhuangfei.smartalert.core.LoadAlert;
import com.zhuangfei.smartalert.core.MessageAlert;
import com.zhuangfei.smartalert.listener.OnChooseViewAdapter;

import cn.lzf.serviceplatform.R;

import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class HistoryScoreFragment extends LazyLoadFragment{

    View mView;

    /**
     * 列表相关
     */
    List<List<Score>> scoreLists = new ArrayList<>();
    List<Map<String, String>> items = new ArrayList<>();
    SimpleAdapter adapter;

    /**
     * 下拉刷新
     */
    private ListView mListView;

    /**
     * 业务类
     */
    private AllScoreService allScoreService;
    private LoginService loginService;
    private MessageAlert messageAlert;
    private ChooseViewAlert chooseViewAlert;

    String term="某学期";
    String[] termArray = { "大一上", "大一下", "大二上", "大二下", "大三上", "大三下", "大四上", "大四下" };
    List<String> termList=new ArrayList<>();
    LinearLayout floatButtonLayout;

    private TextView termTextView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView=inflater.inflate(R.layout.fragment_score_history,container,false);
        return mView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        initView();
        initEvent();
        super.onViewCreated(view,savedInstanceState);
    }

    @Override
    protected void lazyLoad() {
        allScoreService.getAllScore();
    }

    /**
     * 初始化View
     */
    private void initView() {
        messageAlert = new MessageAlert(getActivity()).create();
        chooseViewAlert=new ChooseViewAlert(getActivity());

        // 业务逻辑对象
        allScoreService=new AllScoreService(handler,getActivity());
        loginService = new LoginService(getActivity(),handler);

        mListView = (ListView) mView.findViewById(R.id.id_score_listview);
        floatButtonLayout=(LinearLayout) mView.findViewById(R.id.id_floatbutton);
        termTextView=(TextView) mView.findViewById(R.id.id_allscore_term);

        // 适配器
        adapter = new SimpleAdapter(getActivity(), items, R.layout.item_score_layout, new String[] { "subject", "value" }, new int[] {
                R.id.id_score_name, R.id.id_score_value });
        mListView.setAdapter(adapter);
    }

    private void initEvent() {

        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

                Map map = items.get(arg2);
                String content = "课程名：" + map.get("subject") + "\n课程号：" + map.get("number") + "\n课序号：" + map.get("order")
                        + "\n学分：" + map.get("credit") + "\n成绩：" + map.get("value");
                messageAlert.setTitle("成绩详情").setContent(content).show();
            }

        });

        floatButtonLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                chooseViewAlert.setTitle("选择学期")
                        .setItemTexts(termList)
                        .setOnChooseViewListener(new OnChooseViewAdapter(){
                            @Override
                            public void onItemClick(int index) {
                                showScore(index);
                                chooseViewAlert.dimiss();
                            }
                            @Override
                            public void onCancel(ChooseViewAlert chooseViewAlert) {
                                chooseViewAlert.dimiss();
                            }
                        }).create().show();
            }
        });
    }

    /**
     * 显示课程
     *
     */
    protected void showScore(int index) {
        items.clear();
        if(index<0||scoreLists.size()<=index) return;

        for (Score score : scoreLists.get(index)) {
            term=score.getTerm();
            Map<String, String> map = new HashMap<>();
            map.put("subject", score.getSubject());
            map.put("value", score.getValue());
            map.put("number", score.getNumber());
            map.put("order", score.getOrder());
            map.put("credit", score.getCredit());
            items.add(map);
        }

        adapter.notifyDataSetChanged();
        mListView.setSelection(0);
        termTextView.setText(term);
    }

    public void initTermList(){
        termList.clear();
        for(int i=0;i<scoreLists.size();i++){
            termList.add(termArray[i]);
        }
        floatButtonLayout.setVisibility(View.VISIBLE);
    }

    DefaultHandler handler = new DefaultHandler(getActivity()) {
        public void handleMessage(Message msg) {
            getViewHelper().showSuccessView();
            super.handleMessage(msg);

            switch (msg.what) {

                case HttpConstants.QUERY_ALLSCORE_SUCCESS:
                    // 成绩解析器将返回结果解析为集合
                    AllScoreParser allScoreParser = new AllScoreParser();
                    scoreLists = allScoreParser.parse(msg.obj.toString());
                    showScore(scoreLists.size()-1);
                    initTermList();
                    break;

                // VPN过期
                case HttpConstants.VPN_TOOLONG:
                    if(handler.isIgnoreVpnExpired()){
                        break;
                    }
                    getViewHelper().showLoadingView();
                    loginService.login(ShareTools.get(getActivity(), ShareConstants.STORE_USER, "").toString(), ShareTools
                                    .get(getActivity(), ShareConstants.STORE_PASSWORD1, "").toString(),
                            ShareTools.get(getActivity(), ShareConstants.STORE_PASSWORD2, "").toString());
                    break;

                // 登录成功
                case HttpConstants.LOGIN_SUCCESS:
                    getViewHelper().showLoadingView();
                    ShareTools.put(getActivity(), ShareConstants.STORE_LOGINCOOKIE, (String) msg.obj);
                    allScoreService.getAllScore();
                    break;
            }
        };
    };


    @Override
    public void onDestroy() {
        super.onDestroy();
        if(messageAlert!=null) messageAlert.dimiss();
        if(chooseViewAlert!=null) chooseViewAlert.dimiss();
    }
}
